package com.returnsoft.security.eao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
//import javax.persistence.Query;
import javax.persistence.TypedQuery;

import com.returnsoft.security.dto.DepartmentDto;
import com.returnsoft.security.dto.PermissionDto;
import com.returnsoft.security.entity.Department;
import com.returnsoft.security.exception.EaoExcepcion;
import com.returnsoft.security.exception.SecurityExcepcion;

@LocalBean
@Stateless
public class DepartmentEao implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@PersistenceContext
	private EntityManager em;

	public List<Department> findDepartmentsParent() throws EaoExcepcion {
		try {
			String query = "SELECT d FROM Department d left join d.department dc where dc.id is null";
			TypedQuery<Department> q = em.createQuery(query, Department.class);

			List<Department> departments = q.getResultList();

			return departments;
		} catch (Exception e) {
			e.printStackTrace();
			throw new EaoExcepcion(e.getMessage());
		}
	}

	public List<Department> findDepartmentsChild(Integer departmentId)
			throws EaoExcepcion {
		try {
			String query = "SELECT d FROM Department d left join d.department dc where dc.id = :departmentId";
			TypedQuery<Department> q = em.createQuery(query, Department.class);
			q.setParameter("departmentId", departmentId);
			List<Department> departments = q.getResultList();
			return departments;
		} catch (Exception e) {
			e.printStackTrace();
			throw new EaoExcepcion(e.getMessage());
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<DepartmentDto> findByUser(Integer userId) throws EaoExcepcion {
		try {
			System.out.println("Inicia a buscar departamentos");
			
			String query = "SELECT d.id,d.name " + "FROM Department d "
					+ "left join d.users u " + "where u.id = :userId";
			Query q = em.createQuery(query);
			q.setParameter("userId", userId);
			List<Object[]> departmentsObject = (List<Object[]>) q.getResultList();
			
			List<DepartmentDto> departmentsDto = new ArrayList<DepartmentDto>();
			if (departmentsObject!=null && departmentsObject.size()>0) {
				for (Object[] departmentobject : departmentsObject) {
					Integer departmentId = (Integer) departmentobject[0];
					String departmentName = (String) departmentobject[1];
					
					DepartmentDto departmentDto = new DepartmentDto();
					departmentDto.setId(departmentId);
					departmentDto.setName(departmentName);
					departmentsDto.add(departmentDto);
				}
			}
			
			System.out.println("Termino de buscar departamentos");
			
			return departmentsDto;
		} catch (Exception e) {
			e.printStackTrace();
			throw new EaoExcepcion(e.getMessage());
		}
	}

}
